package com.lxw.config;

import org.springframework.security.authentication.jaas.memory.InMemoryConfiguration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 自定义security配置
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 授权
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 链式编程
        http.authorizeRequests()
                .antMatchers("/").permitAll() // 定义请求"/",任何角色都能访问
                .antMatchers("/level1/**").hasRole("vip1") // 定义请求"/level1/**",只有vip1角色才能访问
                .antMatchers("/level2/**").hasRole("vip2") // 定义请求"/level1/**",只有vip1角色才能访问
                .antMatchers("/level3/**").hasRole("vip3"); // 定义请求"/level1/**",只有vip1角色才能访问

        // 没有权限默认到登录页面
        // 定制登录页
        http.formLogin().loginPage("/toLogin")
                .usernameParameter("user")
                .passwordParameter("pwd")
                .loginProcessingUrl("/login");

        // 开启注销功能
        // 注销成功后返回到指定uri
        http.logout().logoutSuccessUrl("/");

        // 开启记住我功能 -- cookie
        // 默认保存两周
        // 自定义remember参数
        http.rememberMe().rememberMeParameter("remember");

        http.csrf().disable();
    }

    /**
     * 认证
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // 这些数据正常应该从数据库中读取出来
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) // 需要密码加密，否则security认为你不安全
                .withUser("lxw").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3")
                .and()
                .withUser("zs").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");
    }
}
